//
//  MeViewController.m
//  HJZWeiBo
//
//  Created by 蒋晨成 on 16/5/27.
//  Copyright © 2016年 蒋晨成. All rights reserved.
//

#import "MeViewController.h"
#import "MeLoginAndRegistTableViewCell.h"
#import "AppDelegate.h"
#import "WeiboUser.h"
#import "MeDefaultViewController.h"
#import "UserInfoTableViewCell.h"
#import "ThreeButtonTableViewCell.h"
#import "FriendsListViewController.h"
#import "SettingsViewController.h"
#import "UIImage+Extend.h"
#import "HJZMyStatusViewController.h"

@interface MeViewController ()<UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate,RegistAndLoginDelegate, RequestDelegate, WBHttpRequestDelegate, ThreeButtonDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *iconView;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) WeiboUser *user;

@property (nonatomic, strong) UITableView *loginTableView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *imageArray;

@end

@implementation MeViewController
/*

- (void)aiterRequestData {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
      NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    
    [WBHttpRequest requestWithURL:@"https://api.weibo.com/2/place/users/photos.json" httpMethod:@"GET" params:@{@"access_token":accessToken, @"uid":userID} delegate:self withTag:@"@我的"];
    
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data {
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    NSLog(@"%@",dic);
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //[self aiterRequestData];
    self.titleArray = @[@"新的好友", @"微博等级", @"我的相册", @"我的点评", @"我的赞",@"草稿箱",@"微博支付"];
    self.imageArray = @[@"new_friend", @"vip",@"album",@"collect", @"like", @"draft", @"pay"];
    
    self.navigationItem.title = @"我";
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    self.view.backgroundColor = COLOR(230, 230, 230, 1);
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"设置" style: UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction:)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    if (!accessToken) {
        [self setUnloginStateView];
    }else {
        [self requestForUserProfile];
    
    }
    
    
    
    
    if ([self.loginTableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.loginTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.loginTableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.loginTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_tableView]) {
        return 1;
    }else {
        return 2;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_tableView]) {
        return 1;
    }else {
        if (section == 0) {
            return 2;
        }else {
            return 7;
        }
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_tableView]) {
        MeLoginAndRegistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeLoginAndRegistTableViewCell" forIndexPath:indexPath];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                UserInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoTableViewCell" forIndexPath:indexPath];
                cell.user = _user;
                
                return cell;
            }else {
                ThreeButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ThreeButtonTableViewCell" forIndexPath:indexPath];
                cell.delegate = self;
                cell.user = _user;
                return cell;
            }

        }else {
        
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_id"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell_id"];
            }
            
            cell.textLabel.text = _titleArray[indexPath.row];
            cell.imageView.image = [UIImage resizedImageWithName:_imageArray[indexPath.row]];
            return cell;
        }
        
       
    }
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_tableView]) {
        return 40;
    }else {
        return 20;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableView]) {
        return kHeight - 240 - 64;
    }else {
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                return 75;
            }else{
                return 55;
            }
        }else{
            return 50;
        }
        
    }
    
}

#pragma mark --- 设置表头视图 ---
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_tableView]) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 30)];
        UILabel *bigLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 34, 30)];
        bigLabel.text = @"关注";
        [view addSubview:bigLabel];
        UILabel *smallLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 5, 200, 30)];
        smallLabel.text = @"快看看大家都在关注谁";
        smallLabel.font = [UIFont systemFontOfSize:13];
        smallLabel.textColor = [UIColor grayColor];
        view.backgroundColor = [UIColor whiteColor];
        [view addSubview:smallLabel];
        
        UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth - 25, 5, 17, 30)
                               ];
        rightLabel.text= @">";
        [view addSubview:rightLabel];
        
        return view;
    }else {
        return nil;
    }
   
}

#pragma mark --- 滑动时执行的方法 ---
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:_tableView]) {
        CGFloat offsetY = scrollView.contentOffset.y ;
       
        
        CGRect newFrame = self.headImageView.frame;
        if (offsetY >= 0) {
            newFrame.origin.y = -10 - offsetY;
            
        }else if (offsetY >= -100 && offsetY < 0) {
            newFrame.origin.y = -10 - offsetY / 10;
        }else {
            newFrame.origin.y = - 100 - offsetY;
        }
        
        self.headImageView.frame = newFrame;
    }
    
}

#pragma  mark --- 点击导航栏右边的barbutton ---
- (void)rightButtonAction:(UIBarButtonItem *)button {
    
    SettingsViewController *settingVC = [[SettingsViewController alloc] init];
    settingVC.block = ^{
        NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
        if (!accessToken) {
            [self setUnloginStateView];
        }else {
            [self requestForUserProfile];
            
        }
    };
    [self.navigationController pushViewController:settingVC animated:YES];
    
}


#pragma mark --- 点击注册按钮 ---
- (void)registAction:(UIButton *)button {
    [self regist];
}




#pragma mark --- 点击注册方法 ---
- (void)regist {
    [WeiboSDK messageRegister:@"验证码登陆"];
}

#pragma mark --- 点击登录方法 ---
- (void)login {
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.myDelegate = self;
    
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURL;
    request.scope = @"all";
    [WeiboSDK sendRequest:request];

}


#pragma mark --- appdelegate的代理 登录成功返回方法 ---
- (void)requestReceiveWithState:(NSInteger)state {
   
    if (state == 0) {
       [self requestForUserProfile];
    }

    
}


#pragma mark --- 微博SDK请求用户信息 ---
- (void)requestForUserProfile
{
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    
    
    [WBHttpRequest requestForUserProfile:userID withAccessToken:accessToken andOtherProperties:nil queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
    
        _user = (WeiboUser *)result;
        [self.iconView removeFromSuperview];
        [self.headImageView removeFromSuperview];
        [self.tableView removeFromSuperview];
        [self setLoginStateView];
        
        
    }];
}


   


#pragma mark --- 设置登录状态的视图 ---

- (void)setLoginStateView {
    self.loginTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64) style:UITableViewStylePlain];
    self.loginTableView.delegate = self;
    self.loginTableView.dataSource = self;
    
    [self.loginTableView setSeparatorInset:UIEdgeInsetsZero];
    [self.loginTableView setLayoutMargins:UIEdgeInsetsZero];
    
    [self.view addSubview:_loginTableView];
    [self.loginTableView registerClass:[UserInfoTableViewCell class] forCellReuseIdentifier:@"UserInfoTableViewCell"];
    [self.loginTableView registerClass:[ThreeButtonTableViewCell class] forCellReuseIdentifier:@"ThreeButtonTableViewCell"];
    [self.view addSubview:_loginTableView];
    
}

#pragma mark --- 非登录状态的视图 ---
- (void)setUnloginStateView {
    _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -10, kWidth, 300)];
    _headImageView.image = [UIImage imageNamed:@"me_bg.jpg"];
    
    [self.view addSubview:_headImageView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kWidth, kHeight - 64) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.rowHeight = kHeight - 240 - 64;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView registerNib:[UINib nibWithNibName:@"MeLoginAndRegistTableViewCell" bundle:nil] forCellReuseIdentifier:@"MeLoginAndRegistTableViewCell"];
    
    _iconView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    _iconView.backgroundColor = [UIColor clearColor];
    UIButton *iconButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    iconButton.frame = CGRectMake(0, 0, 60, 60);
    [iconButton setBackgroundImage:[UIImage imageNamed:@"head.png"] forState:UIControlStateNormal];
    iconButton.center = _iconView.center;
    [_iconView addSubview:iconButton];
    [iconButton addTarget:self action:@selector(registAction:) forControlEvents:UIControlEventTouchUpInside];
    _tableView.tableHeaderView = _iconView;

}


#pragma mark --- 分栏从左端开始 ---
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_loginTableView]) {
        if ([cell respondsToSelector:@selector(setSeparatorInset:)])
        {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)])
        {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
    }
    
}

#pragma mark --- 点击cell方法 ---

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_loginTableView]) {
        if (indexPath.row == 0 && indexPath.section == 0) {
            MeDefaultViewController *meDefaultVC = [[MeDefaultViewController alloc] init];
            meDefaultVC.user = _user;
            [self.navigationController pushViewController:meDefaultVC animated:YES];
        }
    }

}
#pragma mark --- threebuttonCell的代理 ---
- (void)statusButtonAction {
    HJZMyStatusViewController *statusVC = [[HJZMyStatusViewController alloc] init];
    
    [self.navigationController pushViewController:statusVC animated:YES];
}

- (void)friendsBUttonAction {
    FriendsListViewController *friendVC = [[FriendsListViewController alloc] init];
    friendVC.userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    friendVC.userType = @"friend";
    friendVC.count = [_user.friendsCount integerValue];
    [self.navigationController pushViewController:friendVC animated:YES];
}
- (void)followersButtonActuon {
    FriendsListViewController *friendVC = [[FriendsListViewController alloc] init];
    friendVC.userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    friendVC.userType = @"follower";
    friendVC.count = [_user.friendsCount integerValue];
    [self.navigationController pushViewController:friendVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
